package vn.vfriends.payment.ws;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.payment.jpa.controller.AccountJpaController;
import vn.vfriends.payment.util.Constants;
import vn.vfriends.payment.ws.exception.WSException;

/**
 *
 * @author tuan@vfriends.vn
 */
@WebService(serviceName = "PaymentWS")
public class PaymentWS {

    private static final Logger logger = LoggerFactory.getLogger(PaymentWS.class);
    @Inject
    private AccountJpaController accountController;
    @Resource
    private WebServiceContext wsContext;

    private boolean authenticate() {
        MessageContext messageContext = wsContext.getMessageContext();
        Map headers = (Map) messageContext.get(MessageContext.HTTP_REQUEST_HEADERS);
        List userList = (List)headers.get(Constants.WS_USERNAME);
        List passList = (List)headers.get(Constants.WS_USERNAME);
        
        String username = (userList != null) ? userList.get(0).toString() : "";
        String password = (passList != null) ? passList.get(0).toString() : "";
        
        if("wsuser".equals(username) && "wsuser".equals(password)) {
            return true;
        }
        else {
            return false;
        }
    }
    
    @WebMethod(operationName = "payin")
    public void topup(@WebParam(name = "cif") String cif,
            @WebParam(name = "amount") Long amount,
            @WebParam(name = "source") String source,
            @WebParam(name = "description") String description) throws WSException {
        try {
            boolean isAuthenticated = this.authenticate();
            if(!isAuthenticated) {
                logger.info("Authentication failed");
                throw new WSException(WSException.AUTHENTICATION_FAILED, "Authentication failed");
            }
            
            accountController.topup(cif, amount, source, description);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new WSException(WSException.ERROR, e.getMessage());
        }
    }
}
